<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户活动数量实时展示</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100vh;
            margin: 0;
        }

        #user-activity-count {
            font-size: 24px;
            font-weight: bold;
            margin-top: 20px;
        }
    </style>
</head>

<body>
<h1>实时用户活动数量：<span id="user-activity-count"></span></h1>
<div style="width: 500px;overflow:auto;"><span id="content"></span></div>
<div style="display: flex;justify-content: space-around;margin-top: 20px">
    <button onclick="openLink()">链接</button>

    <button onclick="closeLink()">关闭</button>
</div>
<script>

    // 创建一个 EventSource 实例，连接到 SSE 接口
    var eventSource = null;

    function openLink() {
        eventSource = new EventSource('/user/user-activity-sse')
        var dat = "";

        // 监听 message 事件，当接收到新的数据时触发
        eventSource.onmessage = function (event) {
            const data = JSON.parse(event.data);
            document.getElementById('user-activity-count').textContent = +data.count;
            dat = dat + data.content;
            if (dat.length > 1000) {
                return
            }
            // 将用户活动数量显示在页面上
            document.getElementById('content').textContent = ` ${dat}`;
        };

        // 监听 error 事件，当连接出错时触发
        eventSource.onerror = function (error) {
            console.error('SSE 连接出错:', error);
            // 关闭连接
            eventSource.close();
            document.getElementById('user-activity-count').textContent = '连接出错，请刷新页面重试';
        };
    }

    function closeLink() {
        eventSource.close();
    }


</script>
</body>

</html>